<?php


namespace app\crm\logic;


use app\shop\model\Order;
use think\facade\Db;

class OrderLogic extends AbstractLogic
{

    /**
     * 获取销售新增数据
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-05 10:50
     */
    public function getNewSalesData($userId,array $request): array
    {
        $data = [
            'name'      => '新增订单',
            'num'       => 0,
            'desc'      => '新增订单总金额',
            'value'     => '0元'
        ];
        $sqlWhere = ' status in (1,2,3,4,5)';
        if($request['start_time'] && $request['end_time']){
            $sqlWhere = append_where_sql($sqlWhere,"  create_time BETWEEN " . $request['start_time'] . " AND " . $request['end_time']);
        }
        $dataAuthCustomerId = (new \app\crm\model\Customer())->getDataAuthCustomer($userId, 'order');
        if(in_array(-1,$dataAuthCustomerId)){
            return $data;
        }
        $sqlWhere = !in_array('all', $dataAuthCustomerId)  ? append_where_sql($sqlWhere," uid IN (" . implode(',', $dataAuthCustomerId) . ")") : $sqlWhere;
        $sqlWhere && $sqlWhere = ' where'.$sqlWhere;
        try {
            $sql = "select count(1) total,sum(order_amount ) AS total_amount FROM shrimp_shop_order".$sqlWhere;
            $data = Db::query($sql);
            $data = array_map('intval',$data[0]);
            $data = [
                'name'      => '新增订单',
                'num'       => $data['total'],
                'desc'      => '新增订单总金额',
                'value'     => money_view($data['total_amount'])
            ];
        } catch (\Exception $e) {
        }
        return $data;
    }


    /**
     * 获取消息条件
     * @param $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-12 14:20
     */
    protected function getMessageWhere($request)
    {
        $map = [];
        isset($request['is_progress'])  && $request['is_progress'] && array_push($map, ['o.status','in',[0,1,2,3,4]]) ;
        if(isset($request['return_money_status']) &&  $request['return_money_status']){//回款
            if(in_array($request['return_money_status'],[1,2,3])){
                array_push($map, ['o.status', '>=', $request['return_money_status']]);
                array_push($map, ['o.status', '<', 5]);
                array_push($map, ['o.is_pay', '=', 0]);

            }else if($request['return_money_status'] > 0){
                array_push($map, ['o.status', '=', 4]);
                array_push($map, ['o.receive_time', '<=', time() - $request['return_money_status'] * 86400]);
                array_push($map, ['o.is_pay', '=', 0]);
            }else{
                array_push($map, ['o.status', '=', $request['return_money_status']]);

            }
        }
        return $map;
    }
    /**
     * 今日分配的商机数量
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-09 14:55
     */
    public function getMessageNum($userId,array $request): int
    {
        $count = 0;
        $map = $this->getMessageWhere($request);

        try {
            // 获取客户数据权限 的客户ID
            $dataAuthCustomerId = (new \app\crm\model\Customer())->getDataAuthCustomer($userId, 'order');
            !in_array('all', $dataAuthCustomerId)  && array_push($map, ['o.uid', 'in', $dataAuthCustomerId]);
            $count = Order::alias('o')->where($map)->count();
        }catch (\Exception $e) {
        }
        return $count;
    }

    /**
     * 获取消息列表
     * @param $userId
     * @param array $request
     * @return array
     * @author Mr.Li
     * @create 2021-08-09 15:40
     */
    public function getMessageList($userId,array $request): array
    {
        $data              = [];
        $map = $this->getMessageWhere($request);
        try {
            // 获取客户数据权限 的客户ID
            $dataAuthCustomerId = (new \app\crm\model\Customer())->getDataAuthCustomer($userId, 'order');
            !in_array('all', $dataAuthCustomerId)  && array_push($map, ['o.uid', 'in', $dataAuthCustomerId]);
            $sqlQuery = Order::alias('o')
                ->join('crm_customer c', 'o.uid=c.customer_id', 'LEFT')
                ->join('shop_warehouse h', 'o.house_id=h.id', 'LEFT')
                ->where($map);

            $dataCount  = $sqlQuery->count();

            if ($dataCount) {
                // 订单列表
                $field = ['o.id', 'o.pay_amount', 'o.order_no', 'o.is_pay', 'o.king_num', 'o.king_send_no', 'o.king_sale_no',
                    'o.business_trans_id', 'o.leads_touch_id', 'o.create_time',
                    'o.status', 'c.name as customer_name', 'h.name as house_name'];
                $list = $sqlQuery->field($field)
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->order('o.id DESC')
                    ->select()->toArray();
                if ($list) {
                    $businessTransIdArr = array_column($list, 'business_trans_id');
                    $leadsTouchIdArr    = array_column($list, 'leads_touch_id');
                    $idArr     = array_merge($businessTransIdArr, $leadsTouchIdArr);
                    $userWhere = [
                        ['id', 'in', array_unique($idArr)]
                    ];
                    $userList = Db::name('admin_user')->where($userWhere)->column('realname','id');

                    foreach ($list as $key => $val) {
                        $list[$key]['business_trans_name'] = $userList[$val['business_trans_id']] ?? '';
                        $list[$key]['leads_touch_name']    = $userList[$val['leads_touch_id']] ?? '';
                        $list[$key]['is_pay_name']         = $val['is_pay'] == 1 ? '已支付' : '未支付';
                    }
                }

                if ($list) {
                    foreach($list as &$v){
                        switch ($v['status']) {
                            case '1':
                                $v['status_msg'] = '已审核';
                                break;
                            case '2':
                                $v['status_msg'] = '已下推';
                                break;
                            case '3':
                                $v['status_msg'] = '已发货';
                                break;
                            case '4':
                                $v['status_msg'] = '已收货';
                                break;
                            case '5':
                                $v['status_msg'] = '已完成';
                                break;
                            case '6':
                                $v['status_msg'] = '已作废';
                                break;

                            default:
                                $v['status_msg'] = '待审核';
                                break;
                        }
                    }
                }
            }

            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            $permission = get_user_permission_menu($userId,'order_list_tag');
            $data['menu_list'] = $permission ? $permission : [];
            return $data;
        } catch (\Exception $e) {
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            $permission = get_user_permission_menu($userId,'order_list_tag');
            $data['menu_list'] = $permission ? $permission : [];
        }
        return $data;

    }



}
